package com.tyoj.tyojbackendjudgeservice.codesanbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.tyoj.tyojbackendcommon.common.ErrorCode;
import com.tyoj.tyojbackendcommon.exception.BusinessException;
import com.tyoj.tyojbackendjudgeservice.codesanbox.mode.dto.ExecuteCodeRequest;
import com.tyoj.tyojbackendjudgeservice.codesanbox.CodeSandbox;
import com.tyoj.tyojbackendjudgeservice.codesanbox.mode.dto.ExcuteCodeResponse;


/**
 * 远程调用代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {
    //定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";


    /**
     * 远程执行代码沙箱
     *
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExcuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = "http://localhost:8081/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if (responseStr == null) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteCodeSandbox error,message=" + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExcuteCodeResponse.class);
    }
}
